
#import "MainInsuranceController.h"
#import "InsuranceListHeaderView.h"
#import "InsurancePolicyCell.h"
#import "InsuranceMainCell.h"
#import "InsureDetailListController.h"
#import "JSONFromHkOrderList.h"
#import "UMMobClick/MobClick.h"
#import "PayBDViewController.h"

#define HEIGHT self.view.bounds.size.height
#define MYLINEWIGTH ((UISCREENWEITH/5) - 10)

@interface MainInsuranceController ()<UITableViewDataSource, UITableViewDelegate>
//最上面的滚动滚动视图
@property (nonatomic, strong) InsuranceListHeaderView* topView;
//数组保存滚动视图里面的控制器
@property (nonatomic, strong) NSArray* views;
//记录滚动视图的按钮位置
@property (nonatomic, unsafe_unretained) NSInteger buttonIndex;
@property (nonatomic, strong) UITableView* tableView;
@property (nonatomic, strong) NSMutableArray* products;
@property (nonatomic, strong) MJRefreshAutoGifFooter *footer;
@property (nonatomic, strong) MJRefreshGifHeader *header;
//用一个数来记录用户上拉加载的次数
@property (nonatomic, unsafe_unretained) NSInteger slCount;

@property (nonatomic, strong) ShowNoNetworkView* workView;



@end

@implementation MainInsuranceController

- (NSMutableArray*)products
{
    if (!_products)
    {
        _products = [NSMutableArray array];
    }
    return _products;
}

- (UITableView*)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 40, UISCREENWEITH, UISCREENHEIGHT - 40 - NavigationBarHeight - StatusBarHeight) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = LIGHTGREYColor;
    }
    return _tableView;
}

- (InsuranceListHeaderView*)topView
{
    if (!_topView)
    {
        _topView = [[InsuranceListHeaderView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, 40)];
        _topView.myScrollView.delegate = self;
        _topView.backgroundColor = ClEARColor;
    }
    return _topView;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.h5Str = @"0";
    self.slCount = 1;
    self.topView.buttonTitles = self.titles;
    [self.view addSubview:self.topView];
    if (!self.topView.myScrollView)
    {
        [self.topView scrollView];
    }
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"InsuranceMainCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    self.view.backgroundColor = FFFFFFColor;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:LoadImage(@"back1") style:UIBarButtonItemStylePlain target:self action:@selector(popRootVC)];
    // 关闭系统自动偏移
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.header.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.header = self.header;
    self.footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    // 设置一张图片
    //    [footer setImages:refreshingImages forState:MJRefreshStateRefreshing];
    // Set footer
    self.tableView.footer = self.footer;
    [self.footer setHidden:YES];
    
    [self postHKOrderListWithPageSize:self.slCount withPages:10 withType:self.buttonIndex];

}

- (void)viewWillAppear:(BOOL)animated
{
    [MobClick beginLogPageView:@"MainInsuranceController"];//("PageOne"为页面名称，可自定义)
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(change:) name:@"InsuranceListHeaderView" object:nil];
    self.navigationController.navigationBar.hidden = NO;
    NSLog(@"拿到刷新页面的值：%@",self.h5Str);
    //呈现页面的时候刷新数据(当能获取到是支付完成或者其他那些需要刷新页面的数据时)
    if ([self.h5Str isEqualToString:@"1"])
    {
        self.h5Str = @"0";
        self.slCount = 1;
        [self.products removeAllObjects];
        [self.tableView reloadData];
        [self.tableView.footer resetNoMoreData];
        NSLog(@"self.buttonIndex = %ld",(long)self.buttonIndex);
        [self removeWorkView];
        [self postHKOrderListWithPageSize:self.slCount withPages:10 withType:self.buttonIndex];
        [self.tableView setContentOffset:CGPointMake(0,0) animated:YES];
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"InsuranceListHeaderView" object:nil];
}

- (void)createWorkView
{
    if (self.workView == nil)
    {
        self.workView = [[ShowNoNetworkView alloc]initWithFrame:CGRectMake(0, 40, UISCREENWEITH, self.tableView.frame.size.height)];
        self.workView.labelText = @"暂无记录";
        self.workView.imageName = @"no_record";
        self.workView.myType = MyTypeOfViewForShowError;
        [self.workView createAllSubView];
        [self.view addSubview:self.workView];
    }
}

- (void)removeWorkView
{
    self.workView.frame = CGRectZero;
    [self.workView removeFromSuperview];
    self.workView = nil;
}

//如果没有列表数据就显示一个提示view
- (void)jugdeShowWorkView
{
    if (self.products.count == 0)
    {
        [self createWorkView];
    }
    else
    {
        [self removeWorkView];
    }
}

//下拉刷新
- (void)loadNewData
{
    NSLog(@"下拉刷新");
    self.slCount = 1;
    [self.products removeAllObjects];
    [self.tableView.header beginRefreshing];
    [self.tableView.footer resetNoMoreData];
    NSLog(@"产品数组 =  %@ ++++++++++++++++++++++++++++++;",self.products);
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        [self postHKOrderListWithPageSize:self.slCount withPages:10 withType:self.buttonIndex];
    });
}

//上拉加载
- (void)loadMoreData
{
    self.slCount++;
    NSLog(@"self.slCount = %ld",(long)self.slCount);
    NSLog(@"上拉加载");
//    [self.tableView.footer resetNoMoreData];
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC));
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        [self postHKOrderListWithPageSize:self.slCount withPages:10 withType:self.buttonIndex];
    });
}

/**
 *  停止刷新
 */
-(void)endRefresh
{
    if ([self.tableView.header isRefreshing])
    {
        [self.tableView.header endRefreshing];
    }
    if ([self.tableView.footer isRefreshing])
    {
        [self.tableView.footer endRefreshing];
    }
}

#pragma mark  //获取订单列表

- (void)postHKOrderListWithPageSize:(NSInteger)pageSize withPages:(NSInteger)pages withType:(NSInteger)type
{
    //设置缓存的key
    NSString* cacheStr;
    cacheStr = [NSString stringWithFormat:@"getHKOrderList_%ld_%ld_%@_type%ld",(long)pageSize,(long)pages,[NSString stringWithFormat:@"%ld",(long)self.isSort],(long)type];
    NSDictionary* json;
    // [TRUserAgenCode getCustomerId];
    if (self.isSort)
    {
        json = @{@"platformType":@"1",
                 @"orderType":@"01",
                 @"requestService":@"getHKOrderList",
                 @"requestObject":@{@"customerId":[TRUserAgenCode getCustomerId],
                                    @"status":[NSString stringWithFormat:@"%ld",(long)type],
                                    @"productType":@"1",
                                    @"pageParams":@{
                                            @"currentPage":[NSString stringWithFormat:@"%ld",(long)pageSize],
                                            @"pageSize":[NSString stringWithFormat:@"%ld",(long)pages],
                                            @"queryAll":@"false"}
                                    }
                 };
    }
    else
    {
        json = @{@"platformType":@"1",
                 @"orderType":@"01",
                 @"requestService":@"getHKOrderList",
                 @"requestObject":@{@"customerId":[TRUserAgenCode getCustomerId],
                                    @"status":[NSString stringWithFormat:@"%ld",(long)type],
                                    @"productType":@"4",
                                    @"pageParams":@{
                                            @"currentPage":[NSString stringWithFormat:@"%ld",(long)pageSize],
                                            @"pageSize":[NSString stringWithFormat:@"%ld",(long)pages],
                                            @"queryAll":@"false"}
                                    }
                 };
    }
    NSLog(@"json = %@",json);
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
    [self getHKOrderListWithURL:url withParam:json withCacheStr:cacheStr];
    NSLog(@"url = %@",url);
}

//读取网络或本地的订单列表数据
- (void)readHKOrderListWithData:(NSData*)data
{
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"获取订单列表json = %@",json);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if ([json isKindOfClass:[NSDictionary class]] && json)
        {
            if ([json[@"resultCode"] isEqualToString:@"0"])
            {
                for (NSDictionary* dict in json[@"responseObject"][@"orderHKList"])
                {
                    JSONFromHkOrderList* product = [JSONFromHkOrderList HkOrderListWithJSON:dict];
                    [self.products addObject:product];
                }
                if ([json[@"responseObject"][@"pageParams"] isKindOfClass:[NSDictionary class]] && json[@"responseObject"][@"pageParams"])
                {
                    //总条数
                    NSInteger i1 = [json[@"responseObject"][@"pageParams"][@"pageTotal"] integerValue];
                    //当前页
                    NSInteger i2 = [json[@"responseObject"][@"pageParams"][@"currentPage"] integerValue];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.footer setHidden:NO];
                        if (i1 == i2)
                        {
                            [self.tableView.footer noticeNoMoreData];
                        };
                        if ([json[@"responseObject"][@"orderHKList"] count] == 0)
                        {
                            [self.tableView.footer noticeNoMoreData];
                        }
                    });
                }
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.footer setHidden:YES];
                    
                });
            }
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.footer setHidden:YES];
                
            });
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self endRefresh];
            [self jugdeShowWorkView];
            [self.tableView reloadData];
        });
    });
}

- (void)getHKOrderListWithURL:(NSString*)url withParam:(NSDictionary*)param withCacheStr:(NSString*)cacheStr
{
    NSLog(@"cacheStr = %@",cacheStr);
    
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstanceWithTitle:@"检测到您的设备没有连接网络!" withImageStr:@"no_record" withType:0 withFrame:CGRectMake(0, 40, UISCREENWEITH, self.tableView.frame.size.height) withVC:self];
    [networking showNetworkViewWithSuccess:^{
        
        self.tableView.scrollEnabled = YES;
        [self.header setHidden:NO];

        [XHNetworking POST:url parameters:param success:^(NSData *responseObject) {
            //网络读取数据
            [self readHKOrderListWithData:responseObject];
        } failure:^(NSError *error) {
            //        [self endRefresh];
            NSLog(@"error.code = %@",error.userInfo);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self endRefresh];
                [self.footer setHidden:YES];
            });
        }];
        
    } failure:^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.tableView.scrollEnabled = NO;
            [self.footer setHidden:YES];
            [self.header setHidden:YES];
            [self endRefresh];
        });
        
    } click:^(NSInteger type) {
        NSLog(@"点击了什么类型的按钮%ld!",(long)type);
        if (type == 0)
        {
            //弹出网络提示
            
        }
    }];
}

- (void)popRootVC
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [MobClick endLogPageView:@"MainInsuranceController"];
}

//点击最上面滚动视图 改变下面滚动视图的变化
- (void)change:(NSNotification*)notification
{
    self.slCount = 1;
    [self.products removeAllObjects];
    [self.tableView reloadData];
    [self.tableView.footer resetNoMoreData];
    NSInteger index = [notification.userInfo[@"buttonTag"] integerValue];
    if (!self.isSort)
    {
        //寿险
        self.buttonIndex = [self getLongButtonIndexWithIndex:index];
    }
    else
    {
        //短期险
        self.buttonIndex = [self getButtonIdexWithIndex:index];
    }
    NSLog(@"self.buttonIndex = %ld",(long)self.buttonIndex);
    [self removeWorkView];
    [self postHKOrderListWithPageSize:self.slCount withPages:10 withType:self.buttonIndex];
    [self.tableView setContentOffset:CGPointMake(0,0) animated:YES];
}

//寿险顶部按钮传参数
- (NSInteger)getLongButtonIndexWithIndex:(NSInteger)index
{
    switch (index)
    {
        case 0:
            return 0;
            break;
        case 1:
            return 4;
            break;
        case 2:
            return 1;
            break;
        case 3:
            return 2;
            break;
        default:
            return 0;
            break;
    }
}

//短信顶部按钮传参数
- (NSInteger)getButtonIdexWithIndex:(NSInteger)index
{
    switch (index)
    {
        case 0:
            return 0;
            break;
        case 1:
            return 1;
            break;
        case 2:
            return 2;
            break;
        case 3:
            return 3;
            break;
        case 4:
            return 5;
            break;
        default:
            return 0;
            break;
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

//支付or查看详情
- (void)pay:(UIButton*)sender
{
    InsuranceMainCell* cell = (InsuranceMainCell*)[[sender superview]superview];
    NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
    JSONFromHkOrderList* product = self.products[indexPath.row];
    if (![product.payUrl isEqualToString:@""])
    {
        NSLog(@"去支付页面-----------------------------");
        PayBDViewController* bdVC = [[PayBDViewController alloc]initWithNibName:@"PayBDViewController" bundle:nil];
        //拿到H5页面的判断是否刷新页面的值；
        bdVC.returnValueBlock = ^(NSString *strValue) {
            self.h5Str = strValue;
            NSLog(@"拿到刷新页面的值：%@",self.h5Str);
        };
        bdVC.url = product.payUrl;
        bdVC.orderNo = product.orderNo;
        bdVC.index = 0;
        [self.navigationController pushViewController:bdVC animated:YES];
    }
    else if (![product.receiptUrl isEqualToString:@""])
    {
        NSLog(@"提交回执-----------------------------");
        PayBDViewController* bdVC = [[PayBDViewController alloc]initWithNibName:@"PayBDViewController" bundle:nil];
        //拿到H5页面的判断是否刷新页面的值；
        bdVC.returnValueBlock = ^(NSString *strValue) {
            self.h5Str = strValue;
        };
        bdVC.url = product.receiptUrl;
        bdVC.orderNo = product.orderNo;
        bdVC.index = 1;
//        UINavigationController* navi = [[UINavigationController alloc]initWithRootViewController:bdVC];
//        [self presentViewController:navi animated:YES completion:nil];
        [self.navigationController pushViewController:bdVC animated:YES];
    }
    else
    {
        [self pushDetailListVCWithProduct:product];
    }
}

//进入保单详情
- (void)pushDetailListVCWithProduct:(JSONFromHkOrderList*)product
{
    InsureDetailListController* detailVC = [[InsureDetailListController alloc]initWithNibName:@"InsureDetailListController" bundle:nil];
    detailVC.returnValueBlock = ^(NSString *strValue) {
        self.h5Str = strValue;
    };
    if (self.isSort)
    {
        detailVC.myType = InsureDetailListControllerTypeShort;
    }
    else
    {
        detailVC.myType = InsureDetailListControllerTypeLong;
    }
    detailVC.isDownPolicy = product.isDownPolicy;
    detailVC.productName = product.productName;
    detailVC.orderNo = product.orderNo;
    detailVC.picUrl = product.picUrl;
    detailVC.receiptUrl = product.receiptUrl;
    detailVC.payUrl = product.payUrl;
    detailVC.orderId = product.orderId;
    detailVC.payFlag = product.payFlag;
    [self.navigationController pushViewController:detailVC animated:YES];
}


//展示cell数据
- (void)showDataForCellWillCell:(InsuranceMainCell *)cell withIndexPath:(NSIndexPath*)indexPath
{
    JSONFromHkOrderList* product = self.products[indexPath.row];
    cell.statusLabel.text = product.picUrl;
    cell.payButton.layer.cornerRadius = 2.0;
    cell.payButton.layer.masksToBounds = YES;
    cell.payButton.layer.borderColor = KMainColor.CGColor;
    cell.payButton.layer.borderWidth = 1.0;
    [cell.payButton addTarget:self action:@selector(pay:) forControlEvents:UIControlEventTouchUpInside];
    cell.mainLabel.text = product.productName;
    [cell.productImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGE_URL,product.brandLogo]]
                             placeholderImage:[[UIImage alloc]init]];
    if ([product.brandLogo rangeOfString:HTTP].location != NSNotFound)
    {
        [cell.productImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",product.brandLogo]]
                                 placeholderImage:[[UIImage alloc]init]];
    }
    cell.nameLabel.text = product.insCustomerName;
    cell.orderIDLabel.text = product.orderNo;
    cell.priceLabel.text = [NSString stringWithFormat:@"%@元",product.orderAmount];
    cell.timeLabel.text = product.commitedDate;
    NSNumber* number = [CacheData getCache:@"ISSHOWTGF"];
    //如果用户没有设置推广费；默认显示推广费,设置了是否显示推广费如下
    if (number != nil)
    {
        //如果用户设置“显示推广费”
        if ([number boolValue])
        {
            //如果用户的该订单产品的推广费没有；
            if ([product.promotionExpenses isEqualToString:@""] || [product.promotionExpenses isEqualToString:@"无"])
            {
                [self noShowTGFWithCell:cell withProduct:product];
            }
            //如果用户有该订单产品的推广费；
            else
            {
                [self showTGFWithCell:cell withProduct:product];
            }
        }
        //如果用户设置“不显示推广费”
        else
        {
            [self noShowTGFWithCell:cell withProduct:product];
        }
    }
    else
    {
        //如果用户的该订单产品的推广费没有；
        if ([product.promotionExpenses isEqualToString:@""] || [product.promotionExpenses isEqualToString:@"无"])
        {
            [self noShowTGFWithCell:cell withProduct:product];
        }
        //如果用户有该订单产品的推广费；
        else
        {
            [self showTGFWithCell:cell withProduct:product];
        }
    }
}

- (void)showTGFWithCell:(InsuranceMainCell*)cell withProduct:(JSONFromHkOrderList*)product
{
    cell.tuiGuangLabel1.hidden = NO;
    cell.tuiGuangLabel1.text = [NSString stringWithFormat:@"推广费：%@",product.promotionExpenses];
    cell.payButton.frame =CGRectMake(UISCREENWEITH - 90 - 40, 183 + 21 + 3, 90, 30);
    NSLog(@"product.payFlag = %@_____________________",product.payFlag);
    if (![product.payFlag isEqualToString:@""])
    {
        [cell.payButton setTitle:product.payFlag forState:UIControlStateNormal];
    }
    else
    {
        [cell.payButton setTitle:@"查看详情" forState:UIControlStateNormal];
    }
/*
    if (![product.payUrl isEqualToString:@""])
    {
        [cell.payButton setTitle:@"立即支付" forState:UIControlStateNormal];
    }
    else if (![product.receiptUrl isEqualToString:@""])
    {
        [cell.payButton setTitle:@"提交回执" forState:UIControlStateNormal];
    }
    else
    {
        [cell.payButton setTitle:@"查看详情" forState:UIControlStateNormal];
    }
*/
}

- (void)noShowTGFWithCell:(InsuranceMainCell*)cell withProduct:(JSONFromHkOrderList*)product
{
    cell.tuiGuangLabel1.text = @"";
    [cell.tuiGuangLabel1 setHidden:YES];
    cell.payButton.frame =CGRectMake(8, 183 + 21 + 3, 90, 30);
    NSLog(@"product.payFlag = %@_____________________",product.payFlag);
    if (![product.payFlag isEqualToString:@""])
    {
        [cell.payButton setTitle:product.payFlag forState:UIControlStateNormal];
    }
    else
    {
        [cell.payButton setTitle:@"查看详情" forState:UIControlStateNormal];
    }
}

#pragma mark - 列表代理方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.products.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 263.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    InsuranceMainCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    if (self.products.count > 0)
    {
        [self showDataForCellWillCell:cell withIndexPath:indexPath];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"indexPath.row = %ld",(long)indexPath.row);
    JSONFromHkOrderList* product = self.products[indexPath.row];
    InsureDetailListController* detailVC = [[InsureDetailListController alloc]initWithNibName:@"InsureDetailListController" bundle:nil];
    detailVC.returnValueBlock = ^(NSString *strValue) {
        self.h5Str = strValue;
    };
    if (self.isSort)
    {
        detailVC.myType = InsureDetailListControllerTypeShort;
    }
    else
    {
        detailVC.myType = InsureDetailListControllerTypeLong;
    }
    detailVC.isDownPolicy = product.isDownPolicy;
    detailVC.productName = product.productName;
    detailVC.orderNo = product.orderNo;
    detailVC.picUrl = product.picUrl;
    detailVC.receiptUrl = product.receiptUrl;
    detailVC.payUrl = product.payUrl;
    detailVC.orderId = product.orderId;
    detailVC.payFlag = product.payFlag;
    [self.navigationController pushViewController:detailVC animated:YES];
}

@end
